﻿#region File Description
/*-----------------------------------------------------------------------------
 Author: Jose Antonio Gallego
 Date: 24/10/2011
 
 License: Ms-PL
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.

 The example companies, organizations, products, domain names,
 e-mail addresses, logos, people, places, and events depicted
 herein are fictitious.  No association with any real company,
 organization, product, domain name, email address, logo, person,
 places, or events is intended or should be inferred.
-----------------------------------------------------------------------------*/
#endregion


using System;
using System.Device.Location;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Controls.Maps;
using Zombsquare.Models;

namespace Zombsquare
{
    public partial class MapPage : PhoneApplicationPage
    {
        #region Consts

        /// <value>Default map zoom level.</value>
        private const double DefaultZoomLevel = 19.0;

        /// <value>Maximum map zoom level allowed.</value>
        private const double MaxZoomLevel = 21.0;

        /// <value>Minimum map zoom level allowed.</value>
        private const double MinZoomLevel = 1.0;

        #endregion

        #region Fields

        private PushpinModel pmLocation = new PushpinModel()
            {
                Location = DefaultLocation,
                Titulo = "Usted está aquí",
                Icon = new Uri("/Resources/Icons/Pushpins/PushpinLocation.png", UriKind.Relative)
            };
        
        /// <value>Coordinada de localización por defecto.</value>
        private static readonly GeoCoordinate DefaultLocation = new GeoCoordinate(41.652196, -4.728321);

        /// <value>Nivel de zoom del mapa.</value>
        private double _zoom;

        /// <value>Coordinada central del mapa.</value>
        private GeoCoordinate _center;

        #endregion

        #region Properties

        /// <summary>
        /// Obtiene o estableceel nivel de zoom del mapa.
        /// </summary>
        public double Zoom
        {
            get { return _zoom; }
            set
            {
                var coercedZoom = Math.Max(MinZoomLevel, Math.Min(MaxZoomLevel, value));
                if (_zoom != coercedZoom)
                {
                    _zoom = value;                    
                    NotifyPropertyChanged("Zoom");
                }
            }
        }

        /// <summary>
        /// Obtiene o establece la coordinada central del mapa.
        /// </summary>
        public GeoCoordinate Center
        {
            get { return _center; }
            set
            {
                if (_center != value)
                {
                    _center = value;                    
                    NotifyPropertyChanged("Center");
                }
            }
        }
        
        #endregion

        #region Tasks

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            // Vemos si hay un punto al que navegar para centrar en él el mapa.
            if (App.ViewModel.NavigateTo != null)
            {
                Center = App.ViewModel.NavigateTo.Location;
                Zoom = 18;
                Descripcion.Text = App.ViewModel.NavigateTo.Titulo;
                Direccion.Text = App.ViewModel.NavigateTo.SubTitulo;
                _visualStates.RouteState = VisualStates.ShowRoute;
                statusTextBlock.Visibility = System.Windows.Visibility.Collapsed;
                if (_DescriptionTimer.IsEnabled) _DescriptionTimer.Stop();
               _DescriptionTimer.Start();
            }

            App.ViewModel.NavigateTo = null;            
        }

        private void InitializeDefaults()
        {
            // Inicialización de variables a su valor por defecto.
            Zoom = DefaultZoomLevel;            
        }

        private void ChangeMapMode()
        {
            // Cambia el modo de vista del mapa.
            if (Map.Mode is AerialMode)
            {
                Map.Mode = new RoadMode();
            }
            else
            {
                Map.Mode = new AerialMode(true);
            }
        }

        private void CenterLocation()
        {
            bool gps = true;
            
            System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.TryGetValue<bool>("GPS", out gps);

            if (gps)
            {
                trackingOn = !trackingOn;

                if ((trackingOn) && (watcher.Status == GeoPositionStatus.Ready))
                {

                    Center = watcher.Position.Location;

                    DataManager.LimpiarPosiciones();

                    pmLocation.Location = Center;
                }
                else
                    // Centra el mapa en la localización por defecto.
                    Center = DefaultLocation;

                // Resetea el nivel de zoom a su valor por defecto.
                Zoom = DefaultZoomLevel;
            }
            else
            {
                MessageBox.Show("La localización está deshabilitada, se mostrara la ubicación del Mobility Show, si desea habilitarla vaya a la sección de información y configuración");
                // Centra el mapa en la localización por defecto.
                Center = DefaultLocation;

                // Resetea el nivel de zoom a su valor por defecto.
                Zoom = DefaultZoomLevel;
            }

        }

        private void CenterPushpinsPopup(Point touchPoint)
        {
            // Centra el panel emergente de Pushpins en el punto en que se ha tocado la pantalla.
            Canvas.SetTop(PushpinPopup, touchPoint.Y - ListBoxPushpinCatalog.Height / 2);
        }

        private void CreateNewPushpin(object selectedItem, Point point)
        {
            // Creación de un nuevo pushpin.
            GeoCoordinate location;
            Map.TryViewportPointToLocation(point, out location);

            // Se utiliza la coordinada calculada para añadir un nuevo pushpin,
            // basado en el prototipo de pushpin seleccionado,
            var pushpinPrototype = selectedItem as PushpinModel;

            pushpinPrototype.Titulo = pushpinPrototype.TypeName == "PushpinZombie" ? "Zombie": "Civil";
            
            var pushpin = pushpinPrototype.Clone(location, pushpinPrototype.Titulo, pushpinPrototype.SubTitulo);
            
            pushpin.Tipo = pushpinPrototype.TypeName == "PushpinZombie" ? 1 : 0;

            App.ViewModel.Pushpins.Add(pushpin);
        }

        private void Pushpin_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            var pushpin = sender as Pushpin;
            Center = pushpin.Location;
            statusTextBlock.Visibility = System.Windows.Visibility.Collapsed;

            if (pushpin.Tag != null)
            {
                //string[] texto = ((string)pushpin.Tag).Split(new char[] { '#' });

                Descripcion.Text = ((PushpinModel)pushpin.Tag).Titulo;

                //if (texto.Length > 1)
                Direccion.Text = ((PushpinModel)pushpin.Tag).SubTitulo;
            }
            else
            {
                Descripcion.Text = "Desconocido... ¿sera la nada?";
                Direccion.Text = "...";
            }


            _visualStates.RouteState = VisualStates.ShowRoute;

            if (_DescriptionTimer.IsEnabled) _DescriptionTimer.Stop();
            _DescriptionTimer.Start();
        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/AR/ARPage.xaml", UriKind.Relative));
        }

        #endregion

    }
}
